﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


using EShop.Core;
using EShop.Core.Caching;
using EShop.Core.Data;
using EShop.Core.Events;
using EShop.Core.Model.Store;

namespace EShop.Services.Store
{
    public class CategoryService : ICategory
    {
        #region Constants
        private const string CATEGORY_BY_ID_KEY = "Category.Advertise.id-{0}";
        private const string CATEGORY_PATTERN_KEY = "Category.Advertise";
        #endregion

        #region Fields
        private readonly IRepository<Category> _categoryRepository;
        private readonly ICacheManager _cacheManager;
        private readonly IEventPublisher _eventPublisher;
        //private readonly IDbContext _context;
        #endregion

        #region Ctor
        public CategoryService(IRepository<Category> categoryRepository, ICacheManager cacheManager, IEventPublisher eventPublisher)
        {
            _categoryRepository = categoryRepository;
            _cacheManager = cacheManager;
            _eventPublisher = eventPublisher;
        }
        #endregion

        /// <summary>
        /// 添加信息
        /// </summary>
        /// <param name="?"></param>
        /// <returns></returns>
        public int AddCategory(Category model)
        {

            model.Depth = GetDepth(model.CategoryParentId);
            if (model == null) throw new ExtException("NUll Category Model");

            int rs = _categoryRepository.Insert(model);
            if (rs > 0)
            {
                rs = 1;
                //event notification
                _eventPublisher.EntityInserted(model);

            }
            return rs;

        }
        /// <summary>
        /// 修改一条信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateCategory(Category model)
        {

            if (model == null) throw new ExtException("NUll Category Model");

            int rs = _categoryRepository.Update(model);
            if (rs > 0)
            {
                //event notification
                _eventPublisher.EntityUpdated(model);

            }
            return rs > 0 ? true : false;
        }

        /// <summary>
        /// 获取全部的广告
        /// </summary>
        /// <param name="showHidden">是否需要显示未发布的广告</param>
        /// <returns></returns>
        public List<Category> GetAllCategory(bool showHidden = false)
        {
            return _cacheManager.Get(CATEGORY_PATTERN_KEY, () =>
            {
                var query = _categoryRepository.Table;
                if (!showHidden)
                    query = query.Where(c => !c.Published);

                query = query.OrderBy(c => c.Depth);
                var unsortedCategory = query.ToList();

                //sort categories
                return unsortedCategory;
            });

        }

        /// <summary>
        /// 分页列表一个信息
        /// </summary>
        /// <param name="start"></param>
        /// <param name="limit"></param>
        /// <param name="fiter"></param>
        /// <returns></returns>
        public IPagedList<Category> GetCategory(int pageIndex, int pageSize, bool showHidden = false)
        {
            var category = GetAllCategory(showHidden);
            //filter
            return new PagedList<Category>(category, pageIndex, pageSize);
        }

        /// <summary>
        /// 构造字符串
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="fiter"></param>
        /// <returns></returns>
        public List<Category> GetCategoryByParentId(int ParentId, bool? IsSystem, bool showHidden = false)
        {
            var query = _categoryRepository.Table;
            if (!showHidden)
                query = query.Where(c => !c.Published);

            if (IsSystem.HasValue) query = query.Where(c => c.IsSystem == IsSystem.Value);

            query = query.Where(c => c.CategoryParentId == ParentId);
            query = query.OrderBy(c => c.Depth);
            var unsortedCategory = query.ToList();

            //sort categories
            return unsortedCategory;

        }
        /// <summary>
        /// 取得一条信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Category GetCategoryById(int id)
        {
            if (id <= 0)
                return null;
            //格式化缓存条件
            string key = string.Format(CATEGORY_BY_ID_KEY, id);
            return _cacheManager.Get(key, () =>
            {
                var brand = _categoryRepository.GetById(id);
                return brand;
            });
        }
        /// <summary>
        /// 删除一条信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteById(string id)
        {
            var model = _categoryRepository.GetById(id);
            if (model == null)
                throw new ArgumentNullException("NUll Category Model");

            model.Published = false;
            int r = _categoryRepository.Update(model);

            if (r > 0)
            {
                //cache
                _cacheManager.RemoveByPattern(CATEGORY_PATTERN_KEY);

                //event notification
                _eventPublisher.EntityUpdated(model);
            }
            return r > 0 ? true : false;

        }

        /// <summary>
        /// 获得商品分类
        /// </summary>
        /// <returns></returns>
        public List<Category> GetInfoForProduct()
        {
            return GetCategoryByParentId(0, true, false);
        }


        /// <summary>
        /// 取得当前节点深度
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int GetDepth(int id)
        {
            int ret = 0;
            if (id == 0)
            {// 如果为0，则深度为1

                ret = 0;
            }
            else
            {

                var m = GetCategoryById(id);
                ret = m.Depth;

            }
            return ret;

        }

        ///// <summary>
        ///// 获取文章分类
        ///// </summary>
        ///// <param name="pid"></param>
        ///// <returns></returns>
        //public string GetArticleClassInfo(string pid)
        //{

        //    string ret = string.Empty;
        //    Library.SqlProvider.OleDb db = new Library.SqlProvider.OleDb();
        //    DataTable dt = new DataTable();
        //    DataTable dtn = new DataTable();
        //    dt = GetClassinfoByparentid(Convert.ToInt32(pid));
        //    dtn = GetClassinfoByparentid(102);

        //    BLL.JSONHelper jsons = new BLL.JSONHelper();




        //    BuildClassInfo(ref jsons, dt);
        //    BuildClassInfo(ref jsons, dtn);
        //    ret = jsons.ToString();

        //    return ret;
        //}
        ///// <summary>
        ///// 商品列表页面获得上边导航
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public string GetPathById(string id)
        //{

        //    string ret = string.Empty;
        //    StringBuilder str_daohang = new StringBuilder();
        //    DataTable dt = new DataTable();
        //    dt = GetInfoByFiter(" id=" + id);


        //    BuildPath(dt.Rows[0]["parentid"].ToString(), ref str_daohang);
        //    str_daohang.Insert(str_daohang.Length, "&gt;&gt;");
        //    str_daohang.Insert(str_daohang.Length, dt.Rows[0]["classname"].ToString());
        //    str_daohang.Insert(str_daohang.Length, "&gt;");
        //    str_daohang.Insert(0, "<A class=hp href='/'>首页</A>");

        //    ret = str_daohang.ToString();
        //    return ret;
        //}
        ///// <summary>
        ///// 递归通过id构造导航菜单
        ///// </summary>
        ///// <param name="id"></param>
        ///// <param name="str_bu"></param>
        //public void BuildPath(string id, ref StringBuilder str_bun)
        //{


        //    if (id == "0")
        //    {
        //        return;
        //    }
        //    else
        //    {
        //        DataTable dt = new DataTable();
        //        dt = GetInfoByFiter(" id=" + id);
        //        //str_bu.Insert(str_bu.Length,"&gt;&gt;<a href='/index/list?id=");
        //        //str_bu.Insert(str_bu.Length, dt.Rows[0]["id"].ToString());
        //        //str_bu.Insert(str_bu.Length, "' >");
        //        //str_bu.Insert(str_bu.Length, dt.Rows[0]["Classname"].ToString());
        //        //str_bu.Insert(str_bu.Length, "</a>");
        //        StringBuilder str_bu = new StringBuilder();
        //        str_bu.Append("&gt;&gt;<a href='/index/list?id=");
        //        str_bu.Append(dt.Rows[0]["id"].ToString());
        //        str_bu.Append("' >");
        //        str_bu.Append(dt.Rows[0]["Classname"].ToString());
        //        str_bu.Append("</a>");
        //        str_bun.Insert(0, str_bu.ToString());
        //        BuildPath(dt.Rows[0]["parentid"].ToString(), ref str_bun);
        //    }
        //}
        ///// <summary>
        ///// 取得根id
        ///// </summary>
        ///// <param name="id"></param>
        ///// <param name="rootid"></param>
        //public void GetRootId(int id, ref int rootid)
        //{

        //    DataTable dt = GetInfoByFiter(" id=" + id.ToString());
        //    if (dt.Rows[0]["parentid"].ToString() == "0")
        //    {
        //        rootid = id;
        //        return;
        //    }
        //    else
        //    {

        //        GetRootId(Convert.ToInt32(dt.Rows[0]["parentid"].ToString()), ref rootid);
        //    }

        //}
        ///// <summary>
        ///// 取得商品列表页分类列表
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public string GetListClassInfo(string id)
        //{
        //    string ret = string.Empty;
        //    StringBuilder str_html = new StringBuilder();
        //    str_html.Append("<UL>");
        //    if (string.IsNullOrEmpty(id))
        //    {

        //        return ret;
        //    }
        //    int rootid = 0;
        //    GetRootId(Convert.ToInt32(id), ref rootid);
        //    DataTable dt = new DataTable();
        //    dt = GetInfoByFiter(" id=" + rootid.ToString());

        //    str_html.Append("<LI><A href='/index/list?id=");
        //    str_html.Append(dt.Rows[0]["id"].ToString());
        //    str_html.Append(" ' >");
        //    str_html.Append(dt.Rows[0]["classname"].ToString());
        //    str_html.Append("</a></li><UL>");
        //    BuildListClassinfo(ref str_html, dt.Rows[0]["id"].ToString());
        //    str_html.Append("</UL>");

        //    ret = str_html.ToString();
        //    return ret;
        //}


        //public void BuildListClassinfo(ref StringBuilder str_html, string id)
        //{

        //    DataTable dt = GetInfoByFiter(" parentid=" + id);
        //    if (dt.Rows.Count == 0)
        //    {

        //        return;
        //    }
        //    foreach (DataRow dr in dt.Rows)
        //    {

        //        str_html.Append("<li><a  href = '/index/list?id=");
        //        str_html.Append(dr["id"].ToString());
        //        str_html.Append("'  title='");
        //        str_html.Append(dr["classname"].ToString());
        //        str_html.Append("'   style='color:#222222;' >");
        //        str_html.Append(dr["classname"].ToString());
        //        str_html.Append("</a></li>");
        //        BuildListClassinfo(ref str_html, dr["id"].ToString());

        //    }





        //}
        ///// <summary>
        ///// 取得列表页面全部分类
        ///// </summary>
        ///// <returns></returns>
        //public string GetListClassAll()
        //{

        //    string ret = string.Empty;
        //    StringBuilder str_html = new StringBuilder();
        //    DataTable dt = GetClassinfoByparentid(0, true);
        //    foreach (DataRow dr in dt.Rows)
        //    {

        //        str_html.Append("<LI class=beauty><A   href='/index/list?id=");
        //        str_html.Append(dr["id"].ToString());
        //        str_html.Append("'><SPAN>");
        //        str_html.Append(dr["classname"].ToString());
        //        str_html.Append("</SPAN></A></LI>");
        //    }
        //    ret = str_html.ToString();
        //    return ret;

        //}
        ///// <summary>
        ///// 帮助信息左边导航
        ///// </summary>
        ///// <returns></returns>
        //public string GetHelpviews()
        //{

        //    StringBuilder str_footer = new StringBuilder();
        //    DataTable dt = new DataTable();
        //    Models.MClassModels models_class = new Shop.Models.MClassModels();
        //    dt = models_class.GetClassByPidAndFiter("102", "");
        //    int i = 1;
        //    foreach (DataRow dr in dt.Rows)
        //    {

        //        str_footer.Append("<DL class=border-blue-b><DT class='border-blue-b f14 fb' id='hct-");
        //        str_footer.Append(i.ToString());
        //        str_footer.Append("'>");
        //        str_footer.Append(dr["classname"].ToString());
        //        DataTable dtt = new DataTable();
        //        dtt = models_class.GetClassByPidAndFiter(dr["id"].ToString(), "");
        //        foreach (DataRow drt in dtt.Rows)
        //        {

        //            str_footer.Append("<DD><A class=hm-1 href='/index/helpviews?id=");
        //            str_footer.Append(drt["id"].ToString());
        //            str_footer.Append("'>");
        //            str_footer.Append(drt["classname"].ToString());
        //            str_footer.Append("</A> ");

        //        }
        //        str_footer.Append("</DD></DL>");
        //        i = i + 1;

        //    }


        //    string str_footers = str_footer.ToString();
        //    return str_footers;

        //}
        ///// <summary>
        ///// 返回商品展示页分类
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public string GetViewsLeft(string id)
        //{
        //    StringBuilder str_html = new StringBuilder();
        //    str_html.Append("<DIV class='bor1 mb10' id='sort-nav'>");
        //    int rootid = 0;
        //    GetRootId(Convert.ToInt32(id), ref rootid);
        //    DataTable dt = GetInfoByFiter(" id=" + rootid.ToString());
        //    str_html.Append("<DIV class=backcata><A href='/index/list?id=");
        //    str_html.Append(dt.Rows[0]["id"].ToString());
        //    str_html.Append("'>返回所有");
        //    str_html.Append(dt.Rows[0]["classname"].ToString());
        //    str_html.Append("分类</A> </DIV><UL><LI><SPAN class=move>");
        //    str_html.Append(dt.Rows[0]["Classname"].ToString());
        //    str_html.Append("</SPAN><UL>");
        //    BuildStrForViewsClass(ref str_html, dt.Rows[0]["id"].ToString());
        //    str_html.Append("</LI></UL></UL></DIV>");
        //    return str_html.ToString();

        //}

        //private void BuildStrForViewsClass(ref StringBuilder str_html, string id)
        //{

        //    DataTable dt = new DataTable();
        //    dt = GetInfoByFiter(" parentid=" + id);
        //    if (dt.Rows.Count == 0)
        //    {

        //        return;
        //    }
        //    foreach (DataRow dr in dt.Rows)
        //    {

        //        str_html.Append("<LI> <a href='/index/list?id=");
        //        str_html.Append(dr["id"].ToString());
        //        str_html.Append("'  title='");
        //        str_html.Append(dr["classname"].ToString());
        //        str_html.Append("'   style='color:#222222;' >");
        //        str_html.Append(dr["classname"].ToString());
        //        str_html.Append("</a>");
        //        BuildStrForViewsClass(ref str_html, dr["id"].ToString());
        //    }

        //}
        ///// <summary>
        ///// 商品展示上部导航
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public string GetViewsPathById(string id)
        //{

        //    string ret = string.Empty;
        //    StringBuilder str_daohang = new StringBuilder();
        //    DataTable dt = new DataTable();
        //    dt = GetInfoByFiter(" id=" + id);

        //    BuildPathViews(dt.Rows[0]["parentid"].ToString(), ref str_daohang);
        //    str_daohang.Insert(str_daohang.Length, "&gt;&gt;<a href='/index/list?id=");
        //    str_daohang.Insert(str_daohang.Length, dt.Rows[0]["id"].ToString());
        //    str_daohang.Insert(str_daohang.Length, "' ><font color='#FF0000'>");
        //    str_daohang.Insert(str_daohang.Length, dt.Rows[0]["classname"].ToString());
        //    str_daohang.Insert(str_daohang.Length, "</font></a>");
        //    str_daohang.Insert(str_daohang.Length, "&gt;商品详情");
        //    str_daohang.Insert(0, "<A class=hp href='/'>首页</A>");

        //    ret = str_daohang.ToString();
        //    return ret;
        //}
        ///// <summary>
        ///// 递归通过id构造导航菜单(商品展示)
        ///// </summary>
        ///// <param name="id"></param>
        ///// <param name="str_bu"></param>
        //public void BuildPathViews(string id, ref StringBuilder str_bun)
        //{


        //    if (id == "0")
        //    {
        //        return;
        //    }
        //    else
        //    {
        //        DataTable dt = new DataTable();
        //        dt = GetInfoByFiter(" id=" + id);
        //        StringBuilder str_bu = new StringBuilder();
        //        str_bu.Insert(str_bu.Length, "&gt;&gt;<a href='/index/list?id=");
        //        str_bu.Insert(str_bu.Length, dt.Rows[0]["id"].ToString());
        //        str_bu.Insert(str_bu.Length, "' ><font color='#FF0000'>");
        //        str_bu.Insert(str_bu.Length, dt.Rows[0]["Classname"].ToString());
        //        str_bu.Insert(str_bu.Length, "</font></a>");
        //        str_bun.Insert(0, str_bu.ToString());
        //        BuildPathViews(dt.Rows[0]["parentid"].ToString(), ref str_bun);
        //    }
        //}
        ///// <summary>
        ///// 获取所有子id列表包括本身
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public string GetIdList(string id)
        //{

        //    string ret = string.Empty;
        //    StringBuilder str_id = new StringBuilder();
        //    DataTable dt = new DataTable();
        //    str_id.Append(id);
        //    str_id.Append(",");
        //    dt = GetClassinfoByparentid(Convert.ToInt32(id));
        //    foreach (DataRow dr in dt.Rows)
        //    {

        //        str_id.Append(dr["id"].ToString());
        //        str_id.Append(",");
        //        BuildIdList(ref str_id, dr["id"].ToString());
        //    }
        //    ret = str_id.ToString();
        //    ret = ret.Substring(0, (ret.Length - 1));
        //    return ret;

        //}
        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="str_ids"></param>
        ///// <param name="id"></param>
        //public void BuildIdList(ref StringBuilder str_ids, string id)
        //{

        //    DataTable dt = new DataTable();
        //    dt = GetClassinfoByparentid(Convert.ToInt32(id));
        //    foreach (DataRow dr in dt.Rows)
        //    {

        //        str_ids.Append(dr["id"].ToString());
        //        str_ids.Append(",");
        //        BuildIdList(ref str_ids, dr["id"].ToString());
        //    }
        //}
    }
}
